/*
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.tfvc.workingfolder.filesystemtree;

import java.awt.Image;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.UIManager;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.TreeSelectionModel;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.explorer.view.BeanTreeView;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;


/**
 *
 * @author Venkat Ram Akkineni
 */
public final class FileSystemTreePanel extends javax.swing.JPanel implements ExplorerManager.Provider, Lookup.Provider {

    /**
     * Creates new form FileSystemTreePanel
     */
    public FileSystemTreePanel() {
        initComponents();
        lookup = ExplorerUtils.createLookup(getExplorerManager(), getActionMap());
        buildFileSystemTree();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileSystemTreePanelScrollPane = new BeanTreeView();
        ((BeanTreeView) fileSystemTreePanelScrollPane).setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fileSystemTreePanelScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fileSystemTreePanelScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void buildFileSystemTree() {
        File[] roots = FileSystemView.getFileSystemView().getRoots();
        final FileSystemRootChildrenFactory factory = new FileSystemRootChildrenFactory(roots);
        getExplorerManager().setRootContext(new AbstractNode(Children.create(factory, false)) {

            @Override
            public Image getOpenedIcon(int type) {
                return COMPUTER_IMAGE;
            }

            @Override
            public Image getIcon(int type) {
                return COMPUTER_IMAGE;
            }
            
            @Override
            public String getDisplayName() {
                return "Computer";
            }

            @Override
            public String getName() {
                return "Computer";
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane fileSystemTreePanelScrollPane;
    // End of variables declaration//GEN-END:variables

    @Override
    public ExplorerManager getExplorerManager() {
        if(explorerManager == null ) {
            explorerManager = new ExplorerManager();
        }
        return explorerManager;
    }

    @Override
    public Lookup getLookup() {
        return lookup;
    }
    
    private ExplorerManager explorerManager;
    private final Lookup lookup;
    
    public static final Image FILE_IMAGE = ImageUtilities.icon2Image(UIManager.getLookAndFeelDefaults().getIcon("FileView.fileIcon"));
    public static final Image FOLDER_IMAGE = ImageUtilities.icon2Image(UIManager.getLookAndFeelDefaults().getIcon("FileView.directoryIcon"));
    public static final Image COMPUTER_IMAGE = ImageUtilities.loadImage("org/netbeans/modules/tfsnb/tfvc/workingfolder/filesystemtree/computer.jpeg");
    
    private class FileSystemRootChildrenFactory extends ChildFactory {

        public FileSystemRootChildrenFactory(final File[] roots) {
            this.roots = roots;
        }       
        
        @Override
        protected boolean createKeys(List toPopulate) {
            final List<String> rootNames = new ArrayList<>(roots.length);
            nameToRootDirMap = new HashMap<>();
            for(File file: roots) {
                rootNames.add(file.getName());
                nameToRootDirMap.put(file.getName(), file);
            }
            return toPopulate.addAll(rootNames);
        }

        @Override
        protected Node createNodeForKey(Object key) {
            return new FileSystemFolderNode(nameToRootDirMap.get((String) key));
        }
        
        private final File[] roots;
        private Map<String, File> nameToRootDirMap;
    }
}
